package com.newsproject.exception;

import com.newsproject.pojo.Result;
import com.newsproject.pojo.vo.BusinessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {
    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e) {
        return Result.error(e.getCode(), e.getMessage());
    }

    // 处理数据库唯一约束异常
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result<?> handleDataIntegrityViolation(DataIntegrityViolationException e) {
        String rootMsg = ExceptionUtils.getRootCauseMessage(e);

        if (rootMsg.contains("Duplicate entry") && rootMsg.contains("user.username")) {
            String duplicateValue = rootMsg.split("'")[1];
            return Result.error(409, "用户名【" + duplicateValue + "】已被使用");
        }

        return Result.error(500, "数据操作异常：" + rootMsg);
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleValidationException(MethodArgumentNotValidException ex) {
        List<FieldError> errors = ex.getBindingResult().getFieldErrors();
        String errorMsg = errors.stream()
                .map(error -> error.getField() + "：" + error.getDefaultMessage())
                .collect(Collectors.joining("；"));
        return Result.error(400, "参数校验失败：" + errorMsg);
    }

    // 处理其他所有异常
    @ExceptionHandler(Exception.class)
    public Result<?> handleOtherExceptions(Exception e) {
        String rootMsg = ExceptionUtils.getRootCauseMessage(e);
        return Result.error(500, "系统异常：" + rootMsg);
    }


}
